package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.commons.template.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.NearUserVo;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.UserLocation;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.dubbo.api.mongo.UserLocationApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.repository.Near;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TodayBestService {
    @Reference
    private RecommendUserApi recommendUserApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private QuestionApi questionApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    /**
     * 接口名称：今日佳人
     * 需求描述：查询缘分值最高的用户。 首页 进入佳人
     */
    public ResponseEntity<Object> queryTodayBest() {
        //1. 获取登陆用户id
        Long userId = UserHolder.getUserId();
        //2. 调用Api服务，根据用户id查询今日佳人
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(userId);
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setRecommendUserId(10L);
            recommendUser.setScore(70D);
        }
        //3. 创建并封装返回的vo对象
        TodayBestVo vo = new TodayBestVo();
        // 调用抽取的方法，实现把recommendUser转换为vo对象
        this.convertRecommendUserToTodayBestVo(recommendUser,vo);
        return ResponseEntity.ok(vo);
    }

    /**
     * 接口名称：推荐朋友
     * 接口路径：GET/tanhua/recommendation
     * 需求描述：首页 查询推荐用户分页列表
     */
    public ResponseEntity<Object> queryRecommendation(RecommendQueryVo vo) {
        //1. 用户登陆用户id
        Long userId = UserHolder.getUserId();
        //2. 根据登陆用户id，分页查询推荐用户列表
        PageResult pageResult =
                recommendUserApi.queryRecommendation(userId,vo.getPage(),vo.getPagesize());
        //3. 获取分页查询的当前页数据
        List<RecommendUser> list = (List<RecommendUser>) pageResult.getItems();
        if (list == null) {
            // 如果查询为空，推荐用户默认就是id=5-9
            list = new ArrayList<>();
            for (Integer i = 5; i < 10; i++) {
                RecommendUser ru = new RecommendUser();
                ru.setRecommendUserId(i.longValue());
                ru.setScore(70D+i);
                list.add(ru);
            }
        }

        //4. 定义vo集合，封装接口中返回的数据
        List<TodayBestVo> voList = new ArrayList<>();
        //4.1 判断：遍历查询结果
        if (!CollectionUtils.isEmpty(list)) {
            for (RecommendUser recommendUser : list) {
                //4.2 创建vo对象
                TodayBestVo todayBestVo = new TodayBestVo();
                //4.2 封装vo： recommendUser--->todayBestVo
                this.convertRecommendUserToTodayBestVo(recommendUser,todayBestVo);
                //4.3 vo添加到集合
                voList.add(todayBestVo);
            }
        }
        //5. 把封装好的返回的集合数据voList，设置到pageResult中
        pageResult.setItems(voList);
        //6. 返回分页对象
        return ResponseEntity.ok(pageResult);
    }
    /**
     * 抽取方法：实现把RecommendUser推荐用户对象，转换为TodayBestVo对象
     * 使用范围：在首页 推荐今日佳人、推荐用户会调用这个方法
     */
    private void convertRecommendUserToTodayBestVo(
            RecommendUser recommendUser,TodayBestVo vo){
        //3.1 根据推荐用户id查询用户信息
        UserInfo userInfo = userInfoApi.findById(recommendUser.getRecommendUserId());
        //3.2 封装推荐用户信息
        if (userInfo != null) {
            //3.2.1 对象拷贝： userinfo--->vo
            BeanUtils.copyProperties(userInfo,vo);
            //3.2.2 设置tags
            if (userInfo.getTags() != null) {
                vo.setTags(userInfo.getTags().split(","));
            }
            //3.2.3 设置缘分值
            vo.setFateValue(recommendUser.getScore().longValue());
        }
    }

    /**
     * 接口名称：佳人信息
     * 接口路径：GET/tanhua/:id/personalInfo
     */
    public ResponseEntity<Object> queryPersonalInfo(Long recommendUserId) {
        // 1. 根据推荐用户id查询
        UserInfo userInfo = userInfoApi.findById(recommendUserId);

        // 2. 根据登陆用户id、推荐用户id查询缘分值
        // db.recommend_user.find({userId:1,recommendUserId:57})
        Long score = recommendUserApi.queryScore(UserHolder.getUserId(),recommendUserId);

        // 3. 封装vo对象
        TodayBestVo vo = new TodayBestVo();
        if (userInfo != null) {
            BeanUtils.copyProperties(userInfo,vo);
            if (userInfo.getTags() != null) {
                vo.setTags(userInfo.getTags().split(","));
            }
        }
        vo.setFateValue(score);
        // 4. 返回
        return ResponseEntity.ok(vo);
    }

    /**
     * 接口名称：查询陌生人问题
     * 接口路径：GET/tanhua/strangerQuestions
     */
    public ResponseEntity<Object> strangerQuestions(Long userId) {
        // 查询陌生人问题
        Question question = questionApi.findByUserId(userId);
        String content = question!=null ? question.getTxt() : "你喜欢哪些电影？";
        return ResponseEntity.ok(content);
    }

    /**
     * 接口名称：回复陌生人问题
     * 接口路径：POST/tanhua/strangerQuestions
     * 发送的消息数据格式：
     * {"userId":1,"huanXinId":"1","nickname":"","strangerQuestion":"？","reply":""}
     */
    public ResponseEntity<Object> replyQuestion(Long userId, String reply) {
        //1. 根据登陆用户id查询
        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());

        //2. 查询陌生人问题
        Question question = questionApi.findByUserId(userId);

        //3. 准备消息内容
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userInfo.getId().toString());
        map.put("huanXinId",userInfo.getId());
        map.put("nickname", userInfo.getNickname());
        map.put("strangerQuestion", question!=null ? question.getTxt():"你喜欢我吗.？");
        map.put("reply", reply);

        //4. map转换为json字符串，并实现发消息
        String result = JSON.toJSONString(map);

        // 调用template工具类，发送消息
        huanXinTemplate.sendMsg(userId.toString(),result);
        return ResponseEntity.ok(null);
    }

    @Reference
    private UserLocationApi userLocationApi;
    /**
     * 接口名称：搜附近
     */
    public ResponseEntity<Object> searchNear(String gender, Long distance) {
        //1. 获取用户id
        Long userId = UserHolder.getUserId();
        //2. 调用Api服务，根据用户id查询附近用户 (RPC 远程调用)
        List<UserLocationVo> list = userLocationApi.searchNear(userId,distance);
        //3. 创建vo集合并返回
        List<NearUserVo> voList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (UserLocationVo userLocationVo : list) {
                // 附近的人不能包含自己
                if (userLocationVo.getUserId() == userId){
                    continue;
                }
                // 根据附近人的用户id查询
                UserInfo userInfo = userInfoApi.findById(userLocationVo.getUserId());
                // 性别筛选
                if (!userInfo.getGender().equals(gender)) {
                    continue;
                }
                // 创建vo对象
                NearUserVo vo = new NearUserVo();
                vo.setUserId(userInfo.getId());
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());
                voList.add(vo);
            }
        }
        return ResponseEntity.ok(voList);
    }
}
